package research.ui.editors;

import java.sql.Blob;
import java.sql.SQLException;
import java.util.List;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.DefaultXYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.experimental.chart.swt.ChartComposite;

import research.domain.Photo;
import research.domain.Point;
import research.domain.Sample;
import research.entity.Entity;
import research.entity.EntityType;
import research.model.EntityListContentProvider;
import research.model.ListHierarchy;
import research.model.PhotoPointHierarchy;
import research.persistence.PersistenceManager;
import research.ui.editors.input.EntityEditorInput;

public class PhotoEditor extends FormEntityEditor {
	public static String ID = "research.ui.editors.PhotoEditor";
	private ComboViewer sampleCombo;
	private Text name;
	private Text percent_black;
	private Text descr;
	private Label photo_real;
	private Label photo_processing;
	private XYSeries data = new XYSeries("data");
	private Image image_real;
	private Image image_processing;
	
	private Photo getEntity() {
		return (Photo) entity;
	}

	@Override
	protected boolean checkInputEntityType(EntityEditorInput input) {
		return input.getEntity().getType().equals(EntityType.Photo);
	}

	@Override
	protected void fill() {
		this.name.setText(this.getEntity().getName());
		this.percent_black.setText(Double.toString(this.getEntity()
				.getPercent_black()));
		this.descr.setText(this.getEntity().getDescription());

		setComboEntity(sampleCombo, this.getEntity().getSample());

		try {
			Blob blob_real = getEntity().getPhoto_real();
			if (blob_real != null) {
				image_real = new Image(getSite().getShell().getDisplay(),
						blob_real.getBinaryStream());
				photo_real.setLayoutData(new GridData(
						image_real.getBounds().width,
						image_real.getBounds().height));
				photo_real.setImage(image_real);
			}
			Blob blob_processing = getEntity().getPhoto_processing();
			if (blob_processing != null) {
				image_processing = new Image(getSite().getShell().getDisplay(),
						blob_processing.getBinaryStream());
				photo_processing
						.setLayoutData(new GridData(image_processing
								.getBounds().width, image_processing
								.getBounds().height));
				photo_processing.setImage(image_processing);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
	
	@Override
	protected void initialize() {
		if (!isNewEntity()) {
			List<Entity> s = PersistenceManager.getInstance().getDataSource().getChildren(getEntity(), new PhotoPointHierarchy()); 
			for (Entity point : s) {
				getData().add(((Point) point).getX(), ((Point) point).getY());
			}
		}
		
	}

	@Override
	protected boolean readAndValidate() {
		this.getEntity().setName(this.name.getText());
		try {
			this.getEntity().setPercent_black(
					Double.parseDouble(this.percent_black.getText()));
		} catch (NumberFormatException e) {
			MessageDialog.openWarning(getSite().getShell(), "Error",
					"Ошибка в процентном соотношении");
			return false;
		}
		this.getEntity().setDescription(this.descr.getText());

		Sample cal = (Sample) getComboEntity(sampleCombo);

		if (cal == null) {
			MessageDialog.openWarning(getSite().getShell(), "Error",
					"Выберите образец");
			return false;
		}

		this.getEntity().setPhoto_real(null);
		this.getEntity().setPhoto_processing(null);
		this.getEntity().setSample(cal);

		return validateText(name);
	}

	@Override
	protected void renderForm() {
		TableWrapData td;
		Label label;
		Section section;
		Composite composite;
		GridData gd;
		
		/*
		 * Research
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL);
		section.setLayoutData(td);
		section.setText("Образец пленки");
		// section.setDescription("Select calander from the list");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(2, false));
		section.setClient(composite);
		gd = new GridData();
		label = toolkit.createLabel(composite, "Выберите образец:");
		label.setLayoutData(gd);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		sampleCombo = new ComboViewer(composite, SWT.DROP_DOWN
				| SWT.READ_ONLY);
		sampleCombo.setContentProvider(new EntityListContentProvider(new ListHierarchy(EntityType.Sample), false));
		sampleCombo.setLabelProvider(new LabelProvider());
		sampleCombo.setInput(PersistenceManager.getInstance());
		gd.widthHint = 100;
		sampleCombo.getCombo().setLayoutData(gd);
		sampleCombo.getCombo().addModifyListener(getTextModifyListener());

		/*
		 * Name
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL_GRAB);
		section.setLayoutData(td);
		section.setText("Название*");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		name = toolkit.createText(composite, "",
				SWT.BORDER);
		gd.widthHint = 100;
		name.setLayoutData(gd);
		name.addModifyListener(getTextModifyListener());

		/*
		 * Percent_black
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR);
		td = new TableWrapData(TableWrapData.FILL);
		section.setLayoutData(td);
		section.setText("Процентное соотношение количества точек");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(2, false));
		section.setClient(composite);
		gd = new GridData();
		label = toolkit.createLabel(composite, "Черных:");
		label.setLayoutData(gd);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		percent_black = toolkit.createText(composite,
				"", SWT.BORDER);
		gd.widthHint = 50;
		percent_black.setLayoutData(gd);
		percent_black.addModifyListener(getTextModifyListener());


		/*
		 * Description
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR
				| Section.EXPANDED | Section.TITLE_BAR | Section.TWISTIE);
		td = new TableWrapData(TableWrapData.FILL_GRAB);
		td.maxHeight = 300;
		section.setLayoutData(td);
		section.setText("Описание");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL);
		descr = toolkit.createText(composite, "",
				SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
		gd.widthHint = 200;
		gd.heightHint = 60;
		descr.setLayoutData(gd);
		descr.addModifyListener(getTextModifyListener());

		/*
		 * Real Photo
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR
				| Section.EXPANDED | Section.TITLE_BAR | Section.TWISTIE);
		td = new TableWrapData(TableWrapData.FILL_GRAB);
		td.maxHeight = 300;
		section.setLayoutData(td);
		section.setText("Изображение до обработки");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData();
		photo_real = toolkit.createLabel(composite, "", SWT.NONE);
		photo_real.setLayoutData(gd);

		/*
		 * Processed Photo
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR
				| Section.EXPANDED | Section.TITLE_BAR | Section.TWISTIE);
		td = new TableWrapData(TableWrapData.FILL_GRAB);
		td.maxHeight = 300;
		section.setLayoutData(td);
		section.setText("Изображение после обработки");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData();
		photo_processing = toolkit.createLabel(composite, "", SWT.NONE);
		photo_processing.setLayoutData(gd);

		/*
		 * Chart
		 */
		section = toolkit.createSection(form.getBody(), Section.TITLE_BAR
				| Section.EXPANDED | Section.TITLE_BAR | Section.TWISTIE);
		td = new TableWrapData(TableWrapData.FILL_GRAB);
		td.maxHeight = 300;
		section.setLayoutData(td);
		section.setText("График");
		composite = toolkit.createComposite(section);
		composite.setLayout(new GridLayout(1, false));
		section.setClient(composite);
		gd = new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL);
		gd.heightHint = 300;
		DefaultXYDataset dataset = new DefaultXYDataset();
		dataset.addSeries("data", getData().toArray());
		JFreeChart chart = ChartFactory.createXYLineChart("", "",
				"", dataset, PlotOrientation.VERTICAL, false, false,
				false);
		chart.setAntiAlias(false);
		ChartComposite comp = new ChartComposite(composite, SWT.NONE, chart,
				true);
		comp.setLayoutData(gd);

	}
	
	public XYSeries getData() {
		return data;
	}

}
